package com.d3works.apps.supplychain.db.repo;

import com.d3works.apps.base.db.Product;
import com.d3works.apps.purchase.db.PurchaseOrder;
import com.d3works.apps.purchase.db.repo.PurchaseOrderRepository;
import com.d3works.apps.supplychain.db.MrpLine;
import com.d3works.inject.Beans;
import java.util.Map;

public class MrpLineManagementRepository extends MrpLineRepository {

  /** set alert if purchase delivery date is to far from proposal */
  @Override
  public Map<String, Object> populate(Map<String, Object> json, Map<String, Object> context) {
    Long mrpLineId = (Long) json.get("id");
    MrpLine mrpLine = find(mrpLineId);

    Map<String, Object> mrpLineMap = super.populate(json, context);
    if (mrpLine.getEstimatedDeliveryMrpLine() != null
        && mrpLine.getMaturityDate() != null
        && !mrpLine.getMaturityDate().isEqual(mrpLine.getDeliveryDelayDate())) {
      json.put("respectDeliveryDelayDate", mrpLine.getDeliveryDelayDate());
    } else if (mrpLine.getMrpLineType().getElementSelect()
            == MrpLineTypeRepository.ELEMENT_PURCHASE_PROPOSAL_ESTIMATED_DELIVERY
        && mrpLine.getMaturityDate() != null
        && !mrpLine.getMaturityDate().isEqual(mrpLine.getEstimatedDeliveryDate())) {
      json.put("respectDeliveryDelayDate", mrpLine.getEstimatedDeliveryDate());
    }
    if (PurchaseOrder.class.getName().equals(mrpLine.getProposalSelect())) {
      PurchaseOrder purchaseOrder =
          Beans.get(PurchaseOrderRepository.class).find(mrpLine.getProposalSelectId());
      mrpLine.setIsOutDayNbBetweenPurchaseAndProposal(
          mrpLine.getProduct() != null
              && mrpLine.getMaturityDate() != null
              && (purchaseOrder.getDeliveryDate() == null
                  || mrpLine.getProduct().getMrpFamily() == null
                  || Math.abs(
                          mrpLine.getMaturityDate().toEpochDay()
                              - purchaseOrder.getDeliveryDate().toEpochDay())
                      > mrpLine.getProduct().getMrpFamily().getDayNbBetweenPurchaseAndProposal()));
      json.put(
          "isOutDayNbBetweenPurchaseAndProposal",
          mrpLine.getIsOutDayNbBetweenPurchaseAndProposal());
    }
    return mrpLineMap;
  }

  @Override
  public MrpLine save(MrpLine entity) {
    if (entity.getIsEditedByUser()
        && entity.getMaturityDate() != null
        && entity.getEstimatedDeliveryMrpLine() != null) {
      Product product = entity.getProduct();
      MrpLine mrpLine = entity.getEstimatedDeliveryMrpLine();
      mrpLine.setMaturityDate(entity.getMaturityDate().plusDays(product.getSupplierDeliveryTime()));
      mrpLine.setQty(entity.getQty());
      mrpLine.setIsEditedByUser(true);
      mrpLine.setEstimatedDeliveryDate(
          entity.getMaturityDate().plusDays(product.getSupplierDeliveryTime()));
      entity.setDeliveryDelayDate(
          mrpLine.getMaturityDate().minusDays(product.getSupplierDeliveryTime()));
    }
    return super.save(entity);
  }
}
